const wechatTemplateService = require('./wechatTemplateService')
const smsService = require('./smsService')
const { Message, User } = require('../models')
const logger = require('../utils/logger')

class NotificationService {
  constructor() {
    // 通知类型映射
    this.notificationTypes = {
      POINTS_EARNED: 'points_earned',
      POINTS_CONSUMED: 'points_consumed',
      POINTS_EXPIRE_WARNING: 'points_expire_warning',
      ORDER_STATUS_UPDATE: 'order_status_update',
      MEMBER_UPGRADE: 'member_upgrade',
      INVITE_SUCCESS: 'invite_success',
      SYSTEM_ANNOUNCEMENT: 'system_announcement'
    }
  }

  /**
   * 发送通知（根据用户平台自动选择通知方式）
   * @param {number} userId - 用户ID
   * @param {string} type - 通知类型
   * @param {Object} data - 通知数据
   * @param {Object} options - 选项
   * @returns {Promise<Object>} 发送结果
   */
  async sendNotification(userId, type, data, options = {}) {
    try {
      // 获取用户信息
      const user = await User.findByPk(userId)
      if (!user) {
        throw new Error('用户不存在')
      }

      // 创建站内消息
      const message = await this.createInAppMessage(userId, type, data)

      const results = {
        inApp: { success: true, messageId: message.id },
        wechat: null,
        sms: null
      }

      // 根据用户平台发送对应通知
      if (user.wechatOpenid && !options.skipWechat) {
        try {
          const wechatResult = await this.sendWechatNotification(
            user.wechatOpenid, 
            type, 
            { ...data, userId, messageId: message.id }
          )
          results.wechat = wechatResult
        } catch (error) {
          logger.error('微信通知发送失败:', error)
          results.wechat = { success: false, error: error.message }
        }
      }

      // H5用户或微信通知失败时发送短信
      if (user.phone && (options.forceSms || !user.wechatOpenid || (results.wechat && !results.wechat.success))) {
        try {
          const smsResult = await this.sendSmsNotification(user.phone, type, data)
          results.sms = smsResult
        } catch (error) {
          logger.error('短信通知发送失败:', error)
          results.sms = { success: false, error: error.message }
        }
      }

      return results
    } catch (error) {
      logger.error('发送通知失败:', error)
      throw error
    }
  }

  /**
   * 创建站内消息
   * @param {number} userId - 用户ID
   * @param {string} type - 消息类型
   * @param {Object} data - 消息数据
   * @returns {Promise<Object>} 消息对象
   */
  async createInAppMessage(userId, type, data) {
    try {
      const messageConfig = this.getMessageConfig(type, data)
      
      const message = await Message.create({
        userId,
        type: messageConfig.category,
        title: messageConfig.title,
        content: messageConfig.content,
        extraData: data
      })

      logger.info(`站内消息创建成功: userId=${userId}, type=${type}`)
      return message
    } catch (error) {
      logger.error('创建站内消息失败:', error)
      throw error
    }
  }

  /**
   * 发送微信通知
   * @param {string} openid - 用户openid
   * @param {string} type - 通知类型
   * @param {Object} data - 通知数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendWechatNotification(openid, type, data) {
    try {
      switch (type) {
        case this.notificationTypes.POINTS_EARNED:
          return await wechatTemplateService.sendPointsEarnedNotification(openid, data)
        
        case this.notificationTypes.POINTS_CONSUMED:
          return await wechatTemplateService.sendPointsConsumedNotification(openid, data)
        
        case this.notificationTypes.POINTS_EXPIRE_WARNING:
          return await wechatTemplateService.sendPointsExpireWarning(openid, data)
        
        case this.notificationTypes.ORDER_STATUS_UPDATE:
          return await wechatTemplateService.sendOrderStatusUpdate(openid, data)
        
        case this.notificationTypes.MEMBER_UPGRADE:
          return await wechatTemplateService.sendMemberUpgradeNotification(openid, data)
        
        default:
          throw new Error(`不支持的微信通知类型: ${type}`)
      }
    } catch (error) {
      logger.error('发送微信通知失败:', error)
      throw error
    }
  }

  /**
   * 发送短信通知
   * @param {string} phone - 手机号
   * @param {string} type - 通知类型
   * @param {Object} data - 通知数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendSmsNotification(phone, type, data) {
    try {
      const messageConfig = this.getMessageConfig(type, data)
      const smsContent = this.formatSmsContent(messageConfig.title, messageConfig.content)
      
      // 这里可以根据需要调用短信服务
      // 目前短信服务主要用于验证码，通知类短信可以后续扩展
      logger.info(`短信通知: ${phone} - ${smsContent}`)
      
      return { success: true, content: smsContent }
    } catch (error) {
      logger.error('发送短信通知失败:', error)
      throw error
    }
  }

  /**
   * 获取消息配置
   * @param {string} type - 消息类型
   * @param {Object} data - 消息数据
   * @returns {Object} 消息配置
   */
  getMessageConfig(type, data) {
    switch (type) {
      case this.notificationTypes.POINTS_EARNED:
        return {
          category: 'reward',
          title: '积分到账通知',
          content: `恭喜您获得${data.points}积分！来源：${data.source || '系统奖励'}，当前余额：${data.balance}积分。`
        }
      
      case this.notificationTypes.POINTS_CONSUMED:
        return {
          category: 'consume',
          title: '积分消费通知',
          content: `您已成功消费${data.points}积分，订单号：${data.orderNo || ''}，当前余额：${data.balance}积分。`
        }
      
      case this.notificationTypes.POINTS_EXPIRE_WARNING:
        return {
          category: 'expire',
          title: '积分过期提醒',
          content: `您有${data.expiringPoints}积分将于${data.expireDate}过期，请及时使用。当前余额：${data.currentBalance}积分。`
        }
      
      case this.notificationTypes.ORDER_STATUS_UPDATE:
        const statusMap = {
          processing: '处理中',
          completed: '已完成',
          cancelled: '已取消'
        }
        return {
          category: 'system',
          title: '订单状态更新',
          content: `您的订单${data.orderNo}状态已更新为：${statusMap[data.status] || data.status}。`
        }
      
      case this.notificationTypes.MEMBER_UPGRADE:
        const levelMap = {
          silver: '白银会员',
          gold: '黄金会员',
          diamond: '钻石会员'
        }
        return {
          category: 'system',
          title: '会员等级提升',
          content: `恭喜您升级为${levelMap[data.newLevel] || data.newLevel}！累计积分：${data.totalPoints}，享受更多会员权益。`
        }
      
      case this.notificationTypes.INVITE_SUCCESS:
        return {
          category: 'reward',
          title: '邀请奖励',
          content: `您邀请的好友已成功注册，获得${data.points}积分奖励！继续邀请更多好友获得更多奖励。`
        }
      
      case this.notificationTypes.SYSTEM_ANNOUNCEMENT:
        return {
          category: 'system',
          title: data.title || '系统公告',
          content: data.content || '系统消息'
        }
      
      default:
        return {
          category: 'system',
          title: '系统通知',
          content: data.content || '您有一条新消息'
        }
    }
  }

  /**
   * 格式化短信内容
   * @param {string} title - 标题
   * @param {string} content - 内容
   * @returns {string} 格式化后的短信内容
   */
  formatSmsContent(title, content) {
    // 短信内容需要简洁，去掉多余信息
    return `【打印服务】${title}：${content.substring(0, 50)}${content.length > 50 ? '...' : ''}`
  }

  /**
   * 批量发送通知
   * @param {Array} notifications - 通知列表
   * @returns {Promise<Array>} 发送结果列表
   */
  async sendBatchNotifications(notifications) {
    const results = []
    
    for (const notification of notifications) {
      try {
        const result = await this.sendNotification(
          notification.userId,
          notification.type,
          notification.data,
          notification.options
        )
        results.push({ 
          success: true, 
          userId: notification.userId,
          ...result 
        })
      } catch (error) {
        results.push({ 
          success: false, 
          userId: notification.userId,
          error: error.message 
        })
      }
    }
    
    return results
  }

  /**
   * 发送积分到账通知
   * @param {number} userId - 用户ID
   * @param {Object} data - 通知数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendPointsEarnedNotification(userId, data) {
    return await this.sendNotification(userId, this.notificationTypes.POINTS_EARNED, data)
  }

  /**
   * 发送积分消费通知
   * @param {number} userId - 用户ID
   * @param {Object} data - 通知数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendPointsConsumedNotification(userId, data) {
    return await this.sendNotification(userId, this.notificationTypes.POINTS_CONSUMED, data)
  }

  /**
   * 发送积分过期提醒
   * @param {number} userId - 用户ID
   * @param {Object} data - 通知数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendPointsExpireWarning(userId, data) {
    return await this.sendNotification(userId, this.notificationTypes.POINTS_EXPIRE_WARNING, data)
  }

  /**
   * 发送订单状态更新通知
   * @param {number} userId - 用户ID
   * @param {Object} data - 通知数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendOrderStatusUpdateNotification(userId, data) {
    return await this.sendNotification(userId, this.notificationTypes.ORDER_STATUS_UPDATE, data)
  }

  /**
   * 发送会员升级通知
   * @param {number} userId - 用户ID
   * @param {Object} data - 通知数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendMemberUpgradeNotification(userId, data) {
    return await this.sendNotification(userId, this.notificationTypes.MEMBER_UPGRADE, data)
  }

  /**
   * 发送邀请成功通知
   * @param {number} userId - 用户ID
   * @param {Object} data - 通知数据
   * @returns {Promise<Object>} 发送结果
   */
  async sendInviteSuccessNotification(userId, data) {
    return await this.sendNotification(userId, this.notificationTypes.INVITE_SUCCESS, data)
  }

  /**
   * 发送系统公告
   * @param {Array|number} userIds - 用户ID列表或单个用户ID
   * @param {Object} data - 公告数据
   * @returns {Promise<Array|Object>} 发送结果
   */
  async sendSystemAnnouncement(userIds, data) {
    if (Array.isArray(userIds)) {
      const notifications = userIds.map(userId => ({
        userId,
        type: this.notificationTypes.SYSTEM_ANNOUNCEMENT,
        data
      }))
      return await this.sendBatchNotifications(notifications)
    } else {
      return await this.sendNotification(userIds, this.notificationTypes.SYSTEM_ANNOUNCEMENT, data)
    }
  }
}

module.exports = new NotificationService()